import { CanActivate, ExecutionContext, Injectable } from "@nestjs/common";
import { Reflector } from "@nestjs/core";
import { Request } from "express";

import { AdminSystemRole } from "../constants";
import { REQUIRE_ROLES_KEY } from "../decorator/require-roles.decorator";

@Injectable()
export class RolesCheckGuard implements CanActivate {
    constructor(private reflector: Reflector) {}

    canActivate(context: ExecutionContext): boolean {
        const requiredRoles = this.reflector.getAllAndOverride<ValueOf<typeof AdminSystemRole>[]>(REQUIRE_ROLES_KEY, [
            context.getHandler(),
            context.getClass()
        ]);
        // 如果接口没有设置需要的角色，则不校验角色，直接通过
        if (!requiredRoles) return true;

        const request: Request = context.switchToHttp().getRequest();
        const jwtPayload = request.user; // 从请求中获取解析后的JWT

        // 如果未携带 JWT，也不校验角色，直接通过。比如登录接口
        if (!jwtPayload) return true;

        return requiredRoles.some(role => jwtPayload?.roles?.includes(role));
    }
}
